package com.xh.bussiness.teachbook.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aspose.words.*;
import com.aspose.words.net.System.Data.DataRelation;
import com.aspose.words.net.System.Data.DataRow;
import com.aspose.words.net.System.Data.DataSet;
import com.aspose.words.net.System.Data.DataTable;
import com.xh.bussiness.system.model.PaperTemplate;
import com.xh.bussiness.system.service.IPaperTemplateService;
import com.xh.bussiness.tiku.bean.dto.*;
import com.xh.bussiness.tiku.constant.PaperConstant;
import com.xh.bussiness.tiku.constant.PaperWidthConstant;
import com.xh.bussiness.tiku.constant.QuestionConstant;
import com.xh.bussiness.tiku.model.Question;
import com.xh.bussiness.tiku.service.IQuestionService;
import com.xh.bussiness.tiku.util.ExportQuestionUtils;
import com.xh.bussiness.tiku.util.QuestionUtils;
import com.xh.core.handler.MergeFieldTextbookHtmlHandle;
import com.xh.core.util.FileUtils;
import com.xh.core.util.HandleNodeChangingFontChanger;
import com.xh.core.util.OfficeUtils;
import com.xh.core.util.StringUtils;
import com.xh.tools.question.constant.QuestionTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.*;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author Pitt zhang
 * @since 2020/2/6
 */
@Component
public class PaperUtils {

    private static Logger log = LoggerFactory.getLogger(PaperUtils.class);

    private static IQuestionService _questionService;

    private static IPaperTemplateService _paperTemplateService;

    @Autowired
    private IQuestionService questionService;

    @Autowired
    private IPaperTemplateService paperTemplateService;

    @PostConstruct
    public void init() {
        _questionService = questionService;
        _paperTemplateService = paperTemplateService;
    }

    static {
        try {
            InputStream wordsLicense = OfficeUtils.class.getClassLoader().getResourceAsStream("aspose.words.license.xml");// 凭证文件
            InputStream slidesLicense = OfficeUtils.class.getClassLoader().getResourceAsStream("aspose.slides.license.xml");// 凭证文件
            InputStream cellsLicense = OfficeUtils.class.getClassLoader().getResourceAsStream("aspose.cells.license.xml");// 凭证文件

            com.aspose.slides.License slidesLic = new com.aspose.slides.License();
            slidesLic.setLicense(slidesLicense);
            License wordsLic = new License();
            wordsLic.setLicense(wordsLicense);
            com.aspose.cells.License cellsLic = new com.aspose.cells.License();
            cellsLic.setLicense(cellsLicense);

            //com.aspose.words.FontSettings.getDefaultInstance().setFontsFolder("/Users/david/Documents/Fonts", false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载试卷
     *
     * @param paperDto
     * @param type
     * @param templateId
     * @return
     * @throws Exception
     */
    public static String exportPaperNew(PaperDto paperDto, Integer type, String templateId, HttpServletRequest request, String fileType) throws Exception {
        StringBuffer url = request.getRequestURL();
        String rootPath = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
        String baseTemplate = TeachingBookUtils.class.getResource("/").getFile() + "templates/paper/PaperTemplate.doc";
        //windows Linux 不同路径问题，需要进行路径截取
        if (System.getProperty("file.separator").equals("\\")) {
            baseTemplate = baseTemplate.substring(1);
        }
        // 获取教师上传的模板
        Integer templateType = 1;
        String paperTemplatePath = "";
        if (StringUtils.isNotEmpty(templateId)) {
            PaperTemplate paperTemplate = _paperTemplateService.getById(templateId);
            templateType = paperTemplate.getType();
            //windows Linux 不同路径问题，需要进行路径截取
            if (System.getProperty("file.separator").equals("\\")) {
                paperTemplatePath = rootPath + request.getContextPath() + paperTemplate.getTemplatePath().substring(1);
            } else {
                paperTemplatePath = rootPath + request.getContextPath() + paperTemplate.getTemplatePath();
            }
        } else {
            paperTemplatePath = baseTemplate;
        }
        System.out.println("downloadTemplatePath:" + paperTemplatePath);
        //实例化word模板
        Document srcDoc = new Document(baseTemplate);
        Document doc = new Document(paperTemplatePath);
        if (StringUtils.isNotEmpty(templateId)) {
            for (Section section : srcDoc.getSections()) {
                doc.getFirstSection().appendContent(section);
            }
        }
        // insertHtml 字体处理
        doc.setNodeChangingCallback(new HandleNodeChangingFontChanger(10.5));
        //处理html内容
//        doc.getMailMerge().execute(fieldNames, fieldValues);
        doc.getRange().replace("«paperTitle»", "##" + paperDto.getTitle() + "##", new FindReplaceOptions());
        doc.getRange().replace("«useTime»", paperDto.getUseTime() == null ? "" : paperDto.getUseTime().toString(), new FindReplaceOptions());
        doc.getRange().replace("«totalScore»", paperDto.getTotalScore() == null ? "0" : paperDto.getTotalScore().toString(), new FindReplaceOptions());

        DocumentBuilder builder = new DocumentBuilder(doc);
        builder.getPageSetup().setLeftMargin(65);
        builder.getPageSetup().setRightMargin(65);
        builder.getParagraphFormat().setLineSpacingRule(LineSpacingRule.MULTIPLE);
        builder.getParagraphFormat().setLineSpacing(15.6);
        builder.moveToDocumentEnd();
        Table table = builder.startTable();
        Integer orderNo = 0;
        // 动态获取试卷页面宽度
        PaperWidthConstant paperWidthConstant = PaperWidthConstant.getInstance(templateType);
        // 解析章节试题
        if (!CollectionUtils.isEmpty(paperDto.getPaperCharpts())) {
            //渲染备课模块数据
            for (int i = 0; i < paperDto.getPaperCharpts().size(); i++) {
                PaperChapterDto paperChapter = paperDto.getPaperCharpts().get(i);

                List<PaperQuestionDto> paperQuestionDtos = paperChapter.getQuestions();
                if (CollectionUtils.isEmpty(paperQuestionDtos)) {
                    continue;
                }
                // 题号列
                OfficeUtils.createCellWriteContent(builder, paperWidthConstant.getTOTAL_WIDTH(),
                        NumberUtil.numberToChinese((i + 1)) + "、" + paperChapter.getTitle(), true);
                for (int j = 0; j < paperQuestionDtos.size(); j++) {
                    PaperQuestionDto paperQuestionDto = paperQuestionDtos.get(j);
                    QuestionDto question = _questionService.getQuestion(paperQuestionDto.getQuestionId(), null, true,false,false,false,false);
                    if (question == null) {
                        continue;
                    }
                    question.setOrderNo(orderNo);
                    if (question.getTitle().trim().startsWith("<p>")) {
                        question.setTitle(question.getTitle().trim().replaceFirst("<p>", "").replaceFirst("</p>", ""));
                    }
                    Integer baseType = question.getBasicQuestionType();
                    // 题干列
                    QuestionUtils.formatQuestion(question);
                    if (baseType != null && (baseType.equals(QuestionTypeEnum.READING.getValue()) || baseType.equals(QuestionTypeEnum.CLOZE.getValue())) && paperQuestionDtos.size() > 1) {
                        OfficeUtils.createCellInsertHtml(builder, paperWidthConstant.getTOTAL_WIDTH(),0, "", true);
                        // 阅读理解和完形填空，增加ABCD分隔符
//                        OfficeUtils.createCellInsertHtml(builder, paperWidthConstant.getTOTAL_WIDTH(),
//                                paperWidthConstant.getQUESTION_SPLIT_WIDTH(), QuestionConstant.OPTION_ORDER.split("")[j], true);
                    }
                    if (type.equals(PaperConstant.PAPER_TYPE.TEACHER)) {
                        QuestionUtils.createQuestionTable(paperWidthConstant, rootPath, question, builder, true, true, true, false);

                    } else if (type.equals(PaperConstant.PAPER_TYPE.STUDENT)) {
                        QuestionUtils.createQuestionTable(paperWidthConstant, rootPath, question, builder, true, false, false, false);

                    } else if (type.equals(PaperConstant.PAPER_TYPE.ANALYSIS)) {
                        QuestionUtils.createQuestionTable(paperWidthConstant, rootPath, question, builder, false, true, true, false);

                    } else {
                        //没有类型，按照学生版解析
                        QuestionUtils.createQuestionTable(paperWidthConstant, rootPath, question, builder, true, false, false, false);
                    }
                    orderNo = question.getOrderNo();
                }
            }
        }
        table.clearBorders();
        table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS);
        doc.getRange().replace("\t", "", new FindReplaceOptions());
        String exportPath = request.getSession().getServletContext().getRealPath("/") + "test/export/paper/" + FileUtils.createRandomFilename() + ".doc";
        FileUtils.createFileDirectory(exportPath);
        //定位段落中图片位置垂直居中显示
        int lineHeight = -3;
        NodeCollection childNodes = doc.getChildNodes(NodeType.TABLE, true);
        for (int i = 0; i < childNodes.getCount(); i++) {
            //删除空行
            Table paragraph = (Table) childNodes.get(i);
            if (!paragraph.hasChildNodes()) {
                paragraph.remove();
            }
            NodeCollection collection = paragraph.getChildNodes(NodeType.SHAPE, true);
            for (int j = 0; j < collection.getCount(); j++) {
                Shape shape = (Shape) collection.get(j);
                shape.getFont().setPosition(-shape.getHeight() / 2 - lineHeight);
            }
        }
        doc.save(exportPath, SaveFormat.DOCX);
        if ("pdf".equals(fileType)) {
            String pdfPath = exportPath.substring(0, exportPath.length() - 3) + "pdf";
            OfficeUtils.word2pdf(exportPath, pdfPath, null);
            return pdfPath;
        }
        return exportPath;
    }
    public static String exportPaper(PaperDto paperDto, Integer type, String templateId, HttpServletRequest request, String fileType) throws Exception {
        StringBuffer url = request.getRequestURL();
        String rootPath = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
        String baseTemplate = TeachingBookUtils.class.getResource("/").getFile() + "templates/paper/PaperTemplate.doc";
        //windows Linux 不同路径问题，需要进行路径截取
        if (System.getProperty("file.separator").equals("\\")) {
            baseTemplate = baseTemplate.substring(1);
        }
        // 获取教师上传的模板
        Integer templateType = 1;
        String paperTemplatePath = "";
        if (StringUtils.isNotEmpty(templateId) && !"null".equals(templateId) ) {
            PaperTemplate paperTemplate = _paperTemplateService.getById(templateId);
            templateType = paperTemplate.getType();
            //windows Linux 不同路径问题，需要进行路径截取
            if (System.getProperty("file.separator").equals("\\")) {
                paperTemplatePath = rootPath + request.getContextPath() + paperTemplate.getTemplatePath().substring(1);
            } else {
                paperTemplatePath = rootPath + request.getContextPath() + paperTemplate.getTemplatePath();
            }
        } else {
            paperTemplatePath = baseTemplate;
        }
        System.out.println("downloadTemplatePath:" + paperTemplatePath);
        //实例化word模板
        Document srcDoc = new Document(baseTemplate);
        Document doc = new Document(paperTemplatePath);
        if (StringUtils.isNotEmpty(templateId)) {
            for (Section section : srcDoc.getSections()) {
                doc.getFirstSection().appendContent(section);
            }
        }
        // insertHtml 字体处理
        doc.setNodeChangingCallback(new HandleNodeChangingFontChanger(10.5));
        //处理html内容
//        doc.getMailMerge().execute(fieldNames, fieldValues);
        doc.getRange().replace("«paperTitle»", "##" + paperDto.getTitle() + "##", new FindReplaceOptions());
        doc.getRange().replace("«useTime»", paperDto.getUseTime() == null ? "" : paperDto.getUseTime().toString(), new FindReplaceOptions());
        doc.getRange().replace("«totalScore»", paperDto.getTotalScore() == null ? "0" : paperDto.getTotalScore().toString(), new FindReplaceOptions());

        DocumentBuilder builder = new DocumentBuilder(doc);
        builder.moveToDocumentEnd();
        // 设置左右边距
        builder.getPageSetup().setLeftMargin(65);
        builder.getPageSetup().setRightMargin(65);
        // 设置行间距
        builder.getParagraphFormat().setLineSpacingRule(LineSpacingRule.MULTIPLE);
        builder.getParagraphFormat().setLineSpacing(18);
        Integer orderNo = 0;
        String subjectId = paperDto.getSubjectId();
        // 动态获取试卷页面宽度
//        PaperWidthConstant paperWidthConstant = PaperWidthConstant.getInstance(templateType);
        // 解析章节试题
        if (!CollectionUtils.isEmpty(paperDto.getPaperCharpts())) {
            //渲染备课模块数据
            for (int i = 0; i < paperDto.getPaperCharpts().size(); i++) {
                PaperChapterDto paperChapter = paperDto.getPaperCharpts().get(i);

                List<PaperQuestionDto> paperQuestionDtos = paperChapter.getQuestions();
                if (CollectionUtils.isEmpty(paperQuestionDtos)) {
                    continue;
                }
                builder.writeln(NumberUtil.numberToChinese((i + 1)) + "、" + paperChapter.getTitle());
                for (int j = 0; j < paperQuestionDtos.size(); j++) {
                    PaperQuestionDto paperQuestionDto = paperQuestionDtos.get(j);
                    QuestionDto question = _questionService.getQuestion(paperQuestionDto.getQuestionId(), null, true,false,false,false,false);
                    if (question == null) {
                        continue;
                    }
                    question.setOrderNo(orderNo);
                    Integer baseType = question.getBasicQuestionType();
                    // 题干列
                    ExportQuestionUtils.formatQuestion(subjectId, question);
                    if (baseType != null && (baseType.equals(QuestionTypeEnum.READING.getValue()) || baseType.equals(QuestionTypeEnum.CLOZE.getValue())) && paperQuestionDtos.size() > 1) {
                        if(subjectId.contains("english") || subjectId.contains("yingyu")){
                            builder.insertHtml("<p style='text-align: center;'>"+QuestionConstant.OPTION_ORDER.split("")[j]+"</p>");
                        }else {
                            builder.insertHtml("<p style='text-align: center;'>（"+NumberUtil.numberToChinese((j + 1))+"）</p>");
                        }
                    }
                    if (type.equals(PaperConstant.PAPER_TYPE.TEACHER)) {
                        ExportQuestionUtils.createQuestion(paperQuestionDto.getBlankRowCount(), subjectId, rootPath, question, builder, true, true, true, false);

                    } else if (type.equals(PaperConstant.PAPER_TYPE.STUDENT)) {
                        ExportQuestionUtils.createQuestion(paperQuestionDto.getBlankRowCount(), subjectId, rootPath, question, builder, true, false, false, false);

                    } else if (type.equals(PaperConstant.PAPER_TYPE.ANALYSIS)) {
                        ExportQuestionUtils.createQuestion(paperQuestionDto.getBlankRowCount(), subjectId, rootPath, question, builder, false, true, true, false);

                    } else {
                        //没有类型，按照学生版解析
                        ExportQuestionUtils.createQuestion(paperQuestionDto.getBlankRowCount(), subjectId, rootPath, question, builder, true, false, false, false);
                    }
                    orderNo = question.getOrderNo();
                }
            }
        }
        String exportPath = request.getSession().getServletContext().getRealPath("/") + "test/export/paper/" + FileUtils.createRandomFilename() + ".doc";
        FileUtils.createFileDirectory(exportPath);
        //定位段落中图片位置垂直居中显示
        double lineHeight = -3.5;
        NodeCollection childNodes = doc.getChildNodes(NodeType.PARAGRAPH, true);
        for (int i = 0; i < childNodes.getCount(); i++) {
            //删除空行
            Paragraph paragraph = (Paragraph) childNodes.get(i);
            if (!paragraph.hasChildNodes()) {
                continue;
            }
            NodeCollection collection = paragraph.getChildNodes(NodeType.SHAPE, true);
            for (int j = 0; j < collection.getCount(); j++) {
                Shape shape = (Shape) collection.get(j);
                shape.getFont().setPosition(-shape.getHeight() / 2 - lineHeight);
            }
        }
        doc.save(exportPath, SaveFormat.DOCX);
        if ("pdf".equals(fileType)) {
            String pdfPath = exportPath.substring(0, exportPath.length() - 3) + "pdf";
            OfficeUtils.word2pdf(exportPath, pdfPath, null);
            return pdfPath;
        }
        return exportPath;
    }

    /**
     * 下载试卷word
     *
     * @param paperDto
     * @param request
     * @return
     */
    @Deprecated
    public static String exportPaper(PaperDto paperDto, Integer type, HttpServletRequest request) throws Exception {
        String template = TeachingBookUtils.class.getResource("/").getFile() + "templates/paper/PaperTemplate.doc";
        //windows Linux 不同路径问题，需要进行路径截取
        if (System.getProperty("file.separator").equals("\\")) {
            template = template.substring(1, template.length());
        }
        //封装固定属性和值
        String[] fieldNames = new String[]{
                "paperTitle", "useTime",
                "totalScore"};
        String[] fieldValues = new String[]{
                paperDto.getTitle(), paperDto.getUseTime() == null ? "" : paperDto.getUseTime().toString(),
                paperDto.getTotalScore() == null ? "0" : paperDto.getTotalScore().toString()
        };
        //实例化word模板
        Document doc = new Document(template);
        //处理html内容
        doc.getMailMerge().setFieldMergingCallback(new MergeFieldTextbookHtmlHandle(1, "content"));
        doc.getMailMerge().execute(fieldNames, fieldValues);

        DataSet dataSet = new DataSet();

        //插入备课模块数据
        DataTable paperChapterDataTable = new DataTable("PaperChapterList");
        paperChapterDataTable.getColumns().add("id");
        paperChapterDataTable.getColumns().add("chapterName");

        //插入备课模块明细数据
        DataTable chapterQuestionDataTable = new DataTable("paperQuestion");
        chapterQuestionDataTable.getColumns().add("id");
        chapterQuestionDataTable.getColumns().add("chapterId");
        chapterQuestionDataTable.getColumns().add("orderNo");
        chapterQuestionDataTable.getColumns().add("question");
        chapterQuestionDataTable.getColumns().add("content");

        Map<String, List<String>> questionMap = new HashMap<>();
        DataRow row = null;
        if (!CollectionUtils.isEmpty(paperDto.getPaperCharpts())) {
            //渲染备课模块数据
            for (int i = 0; i < paperDto.getPaperCharpts().size(); i++) {
                PaperChapterDto paperChapter = paperDto.getPaperCharpts().get(i);
                row = paperChapterDataTable.newRow();
                row.set("id", paperChapter.getId());
                row.set("chapterName", NumberUtil.numberToChinese((i + 1)) + "、" + paperChapter.getTitle());
                paperChapterDataTable.getRows().add(row);

                List<PaperQuestionDto> paperQuestionDtos = paperChapter.getQuestions();
                if (CollectionUtils.isEmpty(paperQuestionDtos)) {
                    continue;
                }
                Integer orderNo = 1;
                for (int j = 0; j < paperQuestionDtos.size(); j++) {
                    PaperQuestionDto paperQuestionDto = paperQuestionDtos.get(j);

                    QuestionDto question = _questionService.getQuestion(paperQuestionDto.getQuestionId(), null, true,false,false,false,false);
                    if (question == null) {
                        continue;
                    }
                    question.setQuestionNo(orderNo + ".");
                    DataRow row1 = chapterQuestionDataTable.newRow();
                    row1.set("id", paperQuestionDto.getId());
                    row1.set("chapterId", paperQuestionDto.getPaperChapterId());

                    //添加试题id
                    if (question.getSourceFrom() != null && (question.getSourceFrom().equals(1) || question.getSourceFrom().equals(3))) {
                        //自编题处理
                        String questionHtml = null;
                        if (type.equals(PaperConstant.PAPER_TYPE.TEACHER)) {
                            questionHtml = QuestionUtils.getQuestionHtml(question, true, true, true, false);

                        } else if (type.equals(PaperConstant.PAPER_TYPE.STUDENT)) {
                            questionHtml = QuestionUtils.getQuestionHtml(question, true, false, false, false);

                        } else if (type.equals(PaperConstant.PAPER_TYPE.ANALYSIS)) {
                            questionHtml = QuestionUtils.getQuestionHtml(question, false, true, true, false);

                        } else {
                            //没有类型，按照学生版解析
                            questionHtml = QuestionUtils.getQuestionHtml(question, true, false, false, false);
                        }
                        if (!StringUtils.isEmpty(questionHtml)) {
                            row1.set("content", questionHtml);
                        }
                    } else {
                        row1.set("orderNo", orderNo + ".");
                        row1.set("question", "<" + paperQuestionDto.getQuestionId() + ">");
                        //添加试题id
                        addQuestionToMap(questionMap, paperQuestionDto.getQuestion().getSubjectId(), paperQuestionDto.getQuestionId());
                    }
                    orderNo++;

                    chapterQuestionDataTable.getRows().add(row1);
                }
            }
        }
        dataSet.getTables().add(paperChapterDataTable);
        dataSet.getTables().add(chapterQuestionDataTable);
        //设置层级关系
        String exportPath = request.getSession().getServletContext().getRealPath("/") + "export/paper/" + FileUtils.createRandomFilename() + ".doc";
        dataSet.getRelations().add(new DataRelation("paperQuestion", paperChapterDataTable.getColumns().get("id"), chapterQuestionDataTable.getColumns().get("chapterId")));

        doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_CONTAINING_FIELDS);
        doc.getMailMerge().executeWithRegions(dataSet);
        FileUtils.createFileDirectory(exportPath);

        //定位段落中图片位置垂直居中显示
        int lineHeight = -5;
        NodeCollection childNodes = doc.getChildNodes(NodeType.PARAGRAPH, true);
        for (int i = 0; i < childNodes.getCount(); i++) {
            //删除空行
            Paragraph paragraph = (Paragraph) childNodes.get(i);
            if (!paragraph.hasChildNodes()) {
                paragraph.remove();
            }
            NodeCollection collection = paragraph.getChildNodes(NodeType.SHAPE, true);
            for (int j = 0; j < collection.getCount(); j++) {
                Shape shape = (Shape) collection.get(j);
                shape.getFont().setPosition(-shape.getHeight() / 2 - lineHeight);
            }
        }
        doc.save(exportPath, SaveFormat.DOCX);

        //下载箐优网试题
        List<Map<String, String>> quesFilePathList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(questionMap)) {
            questionMap.forEach((k, v) -> {
                v.forEach(quesId -> {
                    try {
                        Map<String, String> quesFileMap = new HashMap<>();
                        String filePath = _questionService.downloadQuestion(2, k, quesId, request);
                        quesFileMap.clear();
                        quesFileMap.put("fileName", quesId);
                        quesFileMap.put("filePath", filePath);
                        quesFilePathList.add(quesFileMap);
                    } catch (Exception e) {
                        log.error("downloadQuestion have error:" + e.getMessage());
                    }
                });
            });
        }
        //合并试题word
        if (!CollectionUtils.isEmpty(quesFilePathList)) {
            Map<String, String> mergeFiles = new LinkedHashMap<>();
            for (Map<String, String> quesFileMap : quesFilePathList) {
                //todo 获取文件名，替换word
                String fileName = quesFileMap.get("fileName");
                String filePath = quesFileMap.get("filePath");
                if (!StringUtils.isEmpty(fileName) && !StringUtils.isEmpty(filePath)) {
                    mergeFiles.put(fileName, filePath);
                }
            }
            String newExportPath = request.getSession().getServletContext().getRealPath("/") + "export/paper/" + FileUtils.createRandomFilename() + ".docx";
            OfficeUtils.wordsInsert(exportPath, newExportPath, mergeFiles);
            //删除原文件
            FileUtils.delFile(exportPath);
            return newExportPath;
        }
        return exportPath;
    }


    private static void addQuestionToMap(Map<String, List<String>> questionMap, String subject, String
            questionId) {
        if (!StringUtils.isEmpty(subject) && !StringUtils.isEmpty(questionId)) {
            if (questionMap.containsKey(subject)) {
                List<String> quesIds = questionMap.get(subject);
                quesIds.add(questionId);
                questionMap.put(subject, quesIds);
            } else {
                List<String> quesIds = new ArrayList<>();
                quesIds.add(questionId);
                questionMap.put(subject, quesIds);
            }
        }
    }

}
